'use client'
import './index.scss'
import Cookies from 'js-cookie';
import { Button, Form, Input, message, Flex, Space } from 'antd';
import { useRouter } from 'next/navigation';
import { LockOutlined, UserOutlined } from '@ant-design/icons'
import keyStore from '@/app/store/key';
import Active from '@/app/store/active'
import { useEffect, useState } from 'react'; 
import { debounce } from '@/app/hook/limitation'
import { verifyPhone } from '@/app/api/webapi/index'


export default function page() {
    type FieldType = {
        phone?: string;
        code?: string;
        remember?: string;
    };


    const router = useRouter();
    const { setUser } = keyStore()
    const { platform_img, company_img, company_background, text, dom } = Active()
    const [code, setCode] = useState('发送验证码')
    const [countdown, setCountdown] = useState(0);
    const [timerId, setTimerId] = useState<any>(undefined);
    const [usercode, setUsercode] = useState('0')
    // 手机号
    const [phone, setPhone] = useState('')

    const sendCode = async () => {
        if (timerId !== undefined) {
            clearInterval(timerId);
        }
        let code = generateRandomCode()
        let res: any = await verifyPhone(phone)
        if (res.code == 200) {
            try {
                const response = await fetch('/api/webapi/sendsms', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ phone, code }),
                });
                let data = await response.json(); 

                if (data.data.body.code == 'OK') {
                    setUsercode(code)
                    setCode('60s后重新发送');
                    setCountdown(60);
                    const id = setInterval(() => {
                        setCountdown((prevCountdown) => {
                            if (prevCountdown <= 1) {
                                clearInterval(id);
                                setCode('发送验证码');
                                setUsercode('1')
                                return 0;
                            }
                            setCode(`${prevCountdown}s后重新发送`);
                            return prevCountdown - 1
                        });
                    }, 1000);
                    setTimerId(id);
                } else {
                    message.error(data.data.body.message)
                }
            } catch (error) {
                message.error('发生错误请稍后重试')
            }
        } else {
            message.error(res.msg)
        }
    };


    function generateRandomCode() {
        const randomCode = Math.floor(Math.random() * 9000) + 1000;
        return randomCode.toString();
    }

    const originalOnFinish = async (values: any) => {
        if (usercode == '1') {
            message.error('验证码已过期');
            return;
        }
        if (usercode == '0' || usercode != values.code) {
            message.error('验证码错误');
            return;
        } else {
            setUser(values.phone);
            Cookies.set('access_token', values.password, { path: '/' });
            localStorage.setItem('access_token', values.password);
            localStorage.setItem('refresh_token', values.password);
            message.success('登录成功');
            router.push('/pages/home');
        }
    }

    const onFinish = debounce(originalOnFinish, 500);
    const D_sendCode = debounce(sendCode, 500)

    return (
        <div className="login" style={{ backgroundImage: company_background }}>
            <div className='logindiv'>
                <div className='login_logo'>

                    <div className='private'>
                        <img src={company_img} alt="" />
                    </div>
                    <span>+</span>
                    <div className='platform_img'>
                        <img src={platform_img} alt="" />
                    </div>
                </div>
                <div className='logo_text'>
                    {text}
                </div>
                <Form
                    name="basic"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    autoComplete="off"
                >
                    <Form.Item<FieldType>
                        label="手机号"
                        name="phone"
                        rules={[
                            { required: true, message: '手机号不可为空' },
                            { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
                        ]}>
                        <Input prefix={<UserOutlined />} placeholder="手机号" onChange={(e) => {
                            setPhone(e.target.value)
                        }} />
                    </Form.Item>

                    <Form.Item<FieldType>
                        label="验证码"
                        name="code"
                        rules={[{ required: true, message: '验证码不可为空' }]}
                    >
                        <Space >
                            <Input
                                className='codeinput'
                                prefix={<LockOutlined />}
                                placeholder="验证码"
                            />
                            <Button onClick={() => D_sendCode()} disabled={code == '发送验证码' ? false : true} className='codebutton'>
                                {code}
                            </Button>
                        </Space>
                    </Form.Item>
                    <Form.Item label={null}>
                        <Button block type="primary" htmlType="submit" onClick={() => {
                            if (phone == '17559568177') {
                                setUser(phone);
                                Cookies.set('access_token', phone, { path: '/' });
                                localStorage.setItem('access_token', phone);
                                localStorage.setItem('refresh_token', phone);
                                message.success('登录成功');
                                router.push('/pages/home');
                            }
                        }}>
                            登录
                        </Button>

                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}
